package ws_template

import (
	"fmt"
	"go-web-template/domain_template"
	"net/http"

	"github.com/gorilla/websocket"
	"github.com/labstack/echo/v4"
)

type ConnectionClient struct {
	ClientId string
	connection *websocket.Conn
}

var (
	upgrader = websocket.Upgrader{}
	connMap= map[string]ConnectionClient{}
)


func Hello(c echo.Context) error {
	ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
	if err != nil {
		return err
	}
	defer ws.Close()

	for {
		// Write
		err := ws.WriteMessage(websocket.TextMessage, []byte("Hello, Client!"))
		if err != nil {
			c.Logger().Error(err)
		}

		// Read
		_, msg, err := ws.ReadMessage()
		if err != nil {
			c.Logger().Error(err)
		}
		fmt.Printf("%s\n", msg)
	}
}



func HelloUser(c echo.Context) error {
	client_id :=c.Param("client_id")
	ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
	var connClient ConnectionClient
	connClient.ClientId= client_id
	connClient.connection= ws
	connMap[client_id]=connClient
	if err != nil {
		return err
	}
	defer ws.Close()

	for {
		// Write
		err := ws.WriteMessage(websocket.TextMessage, []byte("Hello, Client!"))
		if err != nil {
			c.Logger().Error(err)
		}

		// Read
		_, msg, err := ws.ReadMessage()
		if err != nil {
			c.Logger().Error(err)
		}
		fmt.Printf("%s\n", msg)
	}
}


func WriteMessageToClient(c echo.Context) error{
	// User ID from path `users/:id`
	cm := new(domain_template.ToClientMessage)
	err := c.Bind(&cm)
	if err != nil {
		return c.String(http.StatusBadRequest, "bad request")
	}
	message := cm.ClientMessage
	clientId := cm.ClientId
	// Write
	client := connMap[clientId]
	ws := client.connection

	errws := ws.WriteMessage(websocket.TextMessage, []byte(message))
	if errws != nil {
		c.Logger().Error(errws)
	}

	result := domain_template.SuccessData(cm)

	return c.JSON(http.StatusOK, result)
}